package org.his.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.his.dao.MenuFotonDao;
import org.his.dao.UserDao;
import org.his.pojo.quanxuan.MenuFoton;
import org.his.pojo.quanxuan.User;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    private UserDao userDao;

    private MenuFotonDao menuFotonDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setMenuFotonDao(MenuFotonDao menuFotonDao) {
        this.menuFotonDao = menuFotonDao;
    }

    //用户授权
    @Override
    protected AuthorizationInfo  doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("ni lai 授权验证了！");
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<MenuFoton> menuFotonList = menuFotonDao.getMenuFotonByUserId(user.getUserid());

        Set<String> set = new HashSet<>();
        for (MenuFoton m :
                menuFotonList) {
            set.add(m.getMenulabel());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;
    }

    /**
     * 用户认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("用户认证中......");
        //获取subject（主体），其实就是登陆用户 的 身份信息，也就是用户名、手机号、邮箱
        String principal = (String) token.getPrincipal();
        User user = userDao.login(principal);

        //如果身份信息不正确，返回null，shiro会自动抛出UnkonwAccountExcpetion
        if (user == null){
            return null;
        }

        return new SimpleAuthenticationInfo(user,user.getPassword(),null,"heiha");
    }
}
